package com.lanou.dllo.baisibudejie.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cuneytayyildiz.widget.PullRefreshLayout;
import com.google.gson.Gson;
import com.lanou.dllo.baisibudejie.adapater.JokesAdapter;
import com.lanou.dllo.baisibudejie.R;
import com.lanou.dllo.baisibudejie.entity.JokesResult;
import com.lanou.dllo.baisibudejie.entity.ListEntity;
import com.lanou.dllo.baisibudejie.dialog.ShapeLoadingDialog;


import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/22.
 */
public class JokesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private JokesAdapter adapter;
    private RecyclerView recyclerView;
    private RequestQueue queue;
    private ImageView jokes_item_loveIv;
    private TextView jokes_item_loveTv;
    private PullRefreshLayout pullRefreshLayout;
    private ShapeLoadingDialog dialog;
    private StringRequest request;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }


    /**
     * 在这个方法里面，获取传入的数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    /**
     * 这个方法里面加载布局
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recycler, null);

        return view;
    }


    /**
     * 控件初始化在这写
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView(view);
    }

    private void initView(View v) {

        recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);//初始化RecycleView
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 1);
        recyclerView.setLayoutManager(manager);
        adapter = new JokesAdapter(getActivity());//初始化适配器

        recyclerView.setHasFixedSize(true);
        manager = new GridLayoutManager(getActivity(), 1);
        recyclerView.setLayoutManager(manager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        adapter = new JokesAdapter(getActivity());
        recyclerView.setAdapter(adapter);

        pullRefreshLayout = (PullRefreshLayout) v.findViewById(R.id.pullRefreshLayout);
        pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pullRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                        queue.add(request);
                        pullRefreshLayout.setRefreshing(false);
                    }
                },4000);

            }
        });

        // 此处在现实项目中，请换成网络请求数据代码，sendRequest .....
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            dialog = new ShapeLoadingDialog(getActivity());
            dialog.show();
            initData();
            queue.add(request);
        }
    }

    /**
     * 数据初始化在这写
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        initData();
    }

    private void initData() {

        String per = "50";//数据条数
        queue = Volley.newRequestQueue(getActivity());
        String url = "http://api.budejie.com/api/api_open.php?market=taobao&" +
                "maxid=&udid=359357052150266&a=list&appname=baisibudejie&c=data" +
                "&os=4.3&client=android&page=1&fresh=1&per=" + per +
                "&sub_flag=1&visiting=&type=29&time=week&mac=50%3AFC%3A9F%3AFC%3A75%3A7E&ver" +
                "=6.0.1";
        request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dialog.dismiss();
                        Gson gson = new Gson();
                        JokesResult result = gson.fromJson(response, JokesResult.class);
                        if (result != null) {
                            List<ListEntity> list = result.getList();
                            if (list != null && list.size() > 0) {
                                adapter.addData(list);
                            }
                        }

                    }
                },
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        dialog.dismiss();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                // TODO Auto-generated method stub
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString,
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };

    }


    @Override
    public void onRefresh() {

    }
}
